package com.example.androidproject.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.androidproject.R;
import com.example.androidproject.data.response.LoginResponse;
import com.example.androidproject.net.RetrofitHelper;
import com.example.androidproject.service.config.MusicManager;
import com.example.androidproject.ui.base.IBaseActivity;
import com.example.androidproject.ui.fragment.TestMvpFragment;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hyg.base.data.Constants;
import com.hyg.base.ui.base.BasePresenter;
import com.hyg.base.utils.SaveFileUtils;
import com.hyg.base.utils.StickersListener;
import com.hyg.base.widget.dialog.ProgressDialog;
import com.hyg.common.utils.AppUtils;
import com.hyg.common.utils.LogManager;
import com.hyg.common.utils.LogUtils;
import com.hyg.common.utils.ToastUtils;
import com.hyg.common.utils.language.LocalManageUtil;
import com.hyg.common.utils.language.SPLanguageUtil;
import com.hyg.common.view.dialog.ConfirmDialog;
import com.hyg.idea.net.common.APICallback;
import com.hyg.idea.utils.RxUtil;
import com.liulishuo.okdownload.DownloadTask;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends IBaseActivity implements MusicManager.OnSongChangeListener{

    @BindView(R.id.btn)
    Button button;
    @BindView(R.id.iv_music_play)
    ImageView iv_music_play;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.tv_song_time_all)
    TextView tv_song_time_all;
    @BindView(R.id.tv_song_time)
    TextView tv_song_time;

    private boolean isSeekBarTouch = false;

    private DownloadTask downloadTask;
    private ProgressDialog progressDialog;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        requestPermissions();
        MusicManager.getInstance().init(this);
        MusicManager.getInstance().addOnSongChangeListener(this);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBarTouch = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBarTouch = false;
                MusicManager.getInstance().seekTo(seekBar.getProgress());
            }
        });
    }

    @OnClick({R.id.iv_music_play,R.id.iv_music_pre,R.id.iv_music_next,R.id.btn,R.id.btn1})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn:
                TestMvpFragment.launch(MainActivity.this);
                break;
            case R.id.btn1:
                new ConfirmDialog(this, "发现新版本", "1，新增页面\n2，增加注销账号功能\n3，修复bug", "立即更新", "忽略", new ConfirmDialog.OnConfirmClick() {
                    @Override
                    protected void result(boolean isConfirm) {
                        if(isConfirm) downloadApk("");
                    }
                }).show();
                break;
            case R.id.iv_music_play:
                MusicManager.getInstance().startOrPause();
                break;
            case R.id.iv_music_pre:
                MusicManager.getInstance().playBeforeMusic();
                break;
            case R.id.iv_music_next:
                MusicManager.getInstance().playNext();
                break;
        }
    }

    private void setLanguage(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        String[] strs = new String[]{"简体中文", "英文"};
        dialog.setItems(strs, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case 0:
                        if(SPLanguageUtil.getInstance(MainActivity.this).getSelectLanguage() == 0){
                            return;
                        }
                        LocalManageUtil.saveSelectLanguage(MainActivity.this, 0);
                        break;
                    case 1:
                        if(SPLanguageUtil.getInstance(MainActivity.this).getSelectLanguage() == 2){
                            return;
                        }
                        LocalManageUtil.saveSelectLanguage(MainActivity.this, 2);
                        break;
                }
//                tv_language.setText(strs[which]);
                EventBus.getDefault().post("resetLanguage");
//                MainActivity.this.finish();
            }
        });
        dialog.show();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveMsg(String message) {
        if("resetLanguage".equals(message)){
            reStart(this);
        }
    }

    public void reStart(Context context) {
        finish();
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        overridePendingTransition(0, 0);//清除Activity退出和进入的动画

        // 杀掉进程,会清空缓存
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    protected void onDestroy() {
        LogManager.getInstance().save();
        EventBus.getDefault().unregister(this);
        MusicManager.getInstance().release();
        MusicManager.getInstance().removeOnSongChangeListener(this);
        super.onDestroy();
    }

    private void requestPermissions(){
        XXPermissions.with(this)
                // 不适配 Android 11 可以这样写
                //.permission(Permission.Group.STORAGE)
                // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
                .permission(Permission.MANAGE_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            ToastUtils.show("获取权限成功");
                        } else {
                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show("被永久拒绝授权，请手动授予xxx权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(MainActivity.this, permissions);
                        } else {
                            ToastUtils.show("获取xxx权限失败");
                        }
                    }
                });
    }

    /**
     * Post请求
     */
    public void login() {
        RetrofitHelper.getApiService()
                .login("110120","123456")
//                .login(getParameters())
                .compose(RxUtil.rxSchedulerHelper(this, true))
                .subscribe(new APICallback<LoginResponse>() {
                    @Override
                    public void onSuccess(LoginResponse response) {
                        showToast("登录成功");
                    }

                    @Override
                    public void onFail(String message) {
                        super.onFail(message);

                    }
                });
    }

    private Map<String, Object> getParameters() {
        Map<String, Object> map = new HashMap<>();
//        map.put("username", "分+a%=&控");
        map.put("username", "110120");
        map.put("password", "123456");
        return map;
    }

    /**
     * Get请求
     */
    public void getData() {
        RetrofitHelper.getApiService()
                .getTest()
                .compose(RxUtil.rxSchedulerHelper(this, true))
                .subscribe(new APICallback<String>() {
                    @Override
                    public void onSuccess(String response) {
                        LogUtils.d("aaaaa","Request Success，response is：" + response);
                    }

                    @Override
                    public void onFail(String message) {
                        super.onFail(message);
                    }
                });
    }

    public String formatMiss(int time_mm){
        int time = time_mm / 1000; // 秒
        String mm=(time% 3600)/60>9?(time% 3600)/60+"":"0"+(time% 3600)/60;
        String ss=(time% 3600) % 60>9?(time% 3600) % 60+"":"0"+(time% 3600) % 60;
        return mm+":"+ss;
    }

    @Override
    public void changeSong(int duration, String name, String artist) {
        LogUtils.d("OkHttp","duration = " + duration + "    name = " + name);
        seekBar.setProgress(0);
        button.setText(name);
        tv_song_time_all.setText(formatMiss(duration));
    }

    @Override
    public void onProgress(int duration,int currentPosition) {
        tv_song_time.setText(formatMiss(currentPosition));
        if(!isSeekBarTouch){
            seekBar.setProgress(currentPosition * 100 / duration);
        }
    }

    @Override
    public void onStateChange(boolean isPlaying) {
        if(isPlaying){
            iv_music_play.setImageResource(R.mipmap.music_stop);
        }else {
            iv_music_play.setImageResource(R.mipmap.music_play);
        }
    }

    private void downloadApk(String apkUrl){
//        apkUrl = "http://1.down.kpw9.cn:8021/android_soft2018/yiwan.com_weixinqlpoysanjk.apk";
        apkUrl = "http://gdown.baidu.com/data/wisegame/8d5889f722f640c8/weixin_800.apk";
//        apkUrl = "https://ruichat.oss-cn-shenzhen.aliyuncs.com/5/1634745600/cfcd208495d565ef66e7dff9f98764da/41d58d00f16d42cbbeebe3d8b70cb747.apk";
        progressDialog = new ProgressDialog(this,"版本升级","正在下载安装包，请稍后...");
        progressDialog.show();
        downloadTask = SaveFileUtils.downloadCommonFile(apkUrl,
                Constants.DOWNLOAD_PATH,
                apkUrl.substring(apkUrl.lastIndexOf("/") + 1),
                new StickersListener.StickersProgress() {
                    @Override
                    public void onProgress(int progress) {
                        runOnUiThread(() -> {
                            progressDialog.updateProgress(progress);
                        });
                    }

                    @Override
                    public void onFail() {
                        runOnUiThread(() -> {
                            progressDialog.dismiss();
                            showConfirmDialog("下载失败");
                        });
                    }

                    @Override
                    public void onSuccess(Uri backUri, String path, String name) {
                        runOnUiThread(() -> {
                            progressDialog.updateProgress(0);
                            progressDialog.dismiss();
                        });
                        AppUtils.installApk(MainActivity.this,new File(path),getFileProviderName(MainActivity.this));
                    }
                });
    }

    public String getFileProviderName(Context context){
        return context.getPackageName()+".provider";
    }
}

